﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCServer.Entities.Commands;
using IRCServer.Backend;
using IRCServer.Entities;
using IRCServer.Utilities;
using System.Threading;

namespace IRCServer.CommandHandlers
{
    class USERCommandHandler: UserRegistrationCommandHandler
    {
        public override string HandleCommand(IRCCommandBase command, SessionBase session)
        {
            if (command is USERCommand)
            {
                USERCommand userCommand = (USERCommand)command;
                ClientSession clientSession = (ClientSession)session;

                if (userCommand.Username == null || userCommand.Realname == null || userCommand.Hostname == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NEEDMOREPARAMS, userCommand.CommandName());
                }

                if (clientSession.User == null || clientSession.User.Username == null)
                {
                    if (clientSession.User != null)
                    {
                        clientSession.User.Username = userCommand.Username;
                        clientSession.User.Realname = userCommand.Realname;
                        clientSession.User.Hostname = userCommand.Hostname;
                    }
                    else
                    {
                        clientSession.User = new User()
                        {
                            Username = userCommand.Username,
                            Realname = userCommand.Realname,
                            Hostname = userCommand.Hostname
                        };
                        ServerBackend.Instance.Users.Add(clientSession.User);
                    }

                    if (UpdateConnectionState(clientSession))
                    {
                        Thread thread = new Thread(new ThreadStart(base.AddUserToDaemon));
                        thread.Start();
                    }

                    return String.Empty;
                }
                else
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_ALREADYREGISTERED,String.Empty);
                }
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}
